package com.cskaoyan.utils;

import com.cskaoyan.DatasourceDemo;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建日期: 2022/08/27 10:04
 *
 * @author ciggar
 */
public class DBCPUtils {

    // 数据库连接池
    static DataSource dataSource;

    static {

        try {

            // 创建DBCP的数据库连接池
            Properties properties = new Properties();
//            properties.load(new FileInputStream("target/classes/dbcp.properties"));

            // 获取类加载器
            ClassLoader classLoader = DBCPUtils.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("dbcp.properties");
            properties.load(inputStream);




            dataSource = BasicDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            ex.printStackTrace();
        }


    }


    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }
}
